package com.xiaomengkuan.common.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;

import java.util.Calendar;
import java.util.Map;

/**
 * @author Faraj Mujey
 * -- Creation Time: 2021-01-25 4:19 下午, File Encoding: utf8 --
 */
public class JwtUtil {
    private static final String SIGNATURE;

    static {
        // jwt签名
        SIGNATURE = "baSrhF6WzHzOBQIhm5Trj7Gyhangj1pZnnsFiicrsD!&#&@";
    }

    public static String getToken(Map<String, String> map) {
        JWTCreator.Builder builder = JWT.create();
        // 设置payload
        if (!StringUtils.isEmpty(map))
            map.forEach(builder::withClaim);
        // 设置过期时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, 7); // 7天过期
        // 设置过期时间、返回签名
        return builder.withExpiresAt(calendar.getTime()).sign(Algorithm.HMAC256(SIGNATURE));
    }

    public static DecodedJWT verify(String token) {
        return JWT.require(Algorithm.HMAC256(SIGNATURE)).build().verify(token);
    }

}
